﻿/*
Ugur:
this will scale content based on screen dpi with the thought that buttons, unless wanted otherwise for special cases, should always have the same physical dimensions, no matter which resolution, dpi, screen dimension or screen orientation
that way getting around the issues of UIRoot scaling style PixelPerfect (too small on high dpi screen) and FixedSize (buttons getting scaled based on screen height so one then suddenly has different button dimensions in portrait and landscape screen orientation)

usage: 
-select the gameObject which has the UIRoot script on it
-set UIRoot scaling style to FixedSize
-Add this script to the gameObject which has the UIRoot script on it

Note: in editor, desktop and some specific devices Screen.dpi returns the value 0, in that case either provide a hardcoded value for currentDpi or else in that case the scaling result will be the same as setting PixelPerfect as scaling style in the UIRoot.
*/

using UnityEngine;
using System.Collections;


[RequireComponent(typeof(UIRoot))]

[ExecuteInEditMode]

public class UIRootFixedPhysicalSizeEnforcer : MonoBehaviour
{

    UIRoot mRoot;
    public const float defaultDpi = 160;
    public float currentDpi;


    private float storedScreenWidth;
    private float storedScreenHeight;

    void Awake()
    {
        mRoot = GetComponent<UIRoot>();
        currentDpi = Screen.dpi;
        if (currentDpi == 0f) currentDpi = defaultDpi;
    }



    void Update()
    {
        if (storedScreenWidth != Screen.width || storedScreenHeight != Screen.height)
        {
            float factor = currentDpi / defaultDpi;

            mRoot.manualHeight = Mathf.FloorToInt(Screen.height / factor);

            //Debug.Log("current screen dpi:"+currentDpi+",factor:"+factor+",manualHeight:"+mRoot.manualHeight);

            storedScreenWidth = Screen.width;
            storedScreenHeight = Screen.height;

        }

    }
}